package fr.insta.reverse.uml.servlet;

import java.io.IOException;
import java.lang.reflect.Constructor;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fr.insta.reverse.uml.controller.DefaultController;
import fr.insta.reverse.uml.routing.Route;

public class ServletDispatcher extends HttpServlet
{

	private static final long serialVersionUID = -1903175056433508413L;

	Map<String, Class<? extends DefaultController>> routing = new HashMap<String, Class<? extends DefaultController>>();

	@Override
	public void init(ServletConfig config) throws ServletException
	{
		super.init(config);

		Route[] values = Route.values();

		for (Route route : values)
			routing.put(route.getRoute(), route.getClassController());
	}

	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException
	{
		try
		{
			String route = request.getRequestURI().substring(
					request.getContextPath().length() + 1);

			if (routing.get(route) == null)
				throw new MalformedURLException("La route " + route
						+ " est introuvable ! ");

			request.setAttribute("route", route);

			Constructor<? extends DefaultController> declaredConstructor = routing
					.get(route)
					.getDeclaredConstructor(HttpServletRequest.class,
							HttpServletResponse.class);

			DefaultController controller = declaredConstructor.newInstance(
					request, response);

			if (controller != null)
				controller.execute();

		}
		catch (MalformedURLException _e)
		{
			request.setAttribute("jspFile", "error_404");
			request.setAttribute("route", "error_404");
			request.getRequestDispatcher("/WEB-INF/template.jsp").include(request, response);
		}
		catch (Exception _e)
		{
			_e.printStackTrace();
		}
	}
}
